// pages/firework/check/index.js
var app = getApp(), fetchApi = require("../../../utils/httpPost.js"), 
common_Js = require("../../../component/common.js");

import Dialog from '../../../component/vant/dialog/dialog';
import Toast from '../../../component/vant/toast/toast';
var context = null;// 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;//是否在绘制中
var arrx = [];//动作横坐标
var arry = [];//动作纵坐标
var arrz = [];//总做状态，标识按下到抬起的一个组合
var canvasw = 0;//画布宽度
var canvash = 0;//画布高度



Page({

    /**
     * 页面的初始数据
     */
    data: {
        fire_work_id:0,
        fireWork:{},
        analyses:[],
        submitState:false,
        check_state:0,
        signImg:'',
        is_submit:0,
        fileList1:[],
        user_id:0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.id){
            this.data.fire_work_id = parseInt(options.id);
        }
        if(options.submit){
          this.data.is_submit = parseInt(options.submit)
        }
        this.data.user_id = app.getStorageSync("user_id");
        this.onHttpInit();
        this.startCanvas();
    },

  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this
    fetchApi.httpPost('/fire/work/detail', {
      work_id:that.data.fire_work_id,
    }, function (res) {
      console.log("作业票详情返回数据", res)
      if (res.data.code == 0) {
        that.data.fireWork = res.data.data.fireWork;
        that.data.is_submit = res.data.data.is_submit;
        that.setData({
          is_submit:that.data.is_submit,
          hasData: true,
          fireWork: res.data.data.fireWork,
          analyses:res.data.data.fireWork.analyses,
        })
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  
  deleteImg1: function (res) {
    console.log('删除图片', res)
    var index = res.currentTarget.dataset.index;
    this.data.fileList1 = [];
    this.setData({
      fileList1: this.data.fileList1
    });
  },
  afterRead(event) {
    console.log('afterRead', event)
    const {
      file,
      name
    } = event.detail;
    console.log('afterRead name', name)
    console.log('afterRead file', file)
    const fileList = this.data[`fileList${name}`];

    this.setData({
      [`fileList${name}`]: fileList.concat(file)
    });

    console.log('afterRead fileList', fileList)
    this.data.fileList1.concat(file)
    console.log('fileList', this.data.fileList1)
  },

  submitOp(e){
    var check_state = e.currentTarget.dataset.state;

    // if(this.data.is_submit == 0){
    //   if(this.data.fileList1.length < 2){
    //     Toast("请上传不少于2张现场图片");
    //     return;
    //   }
    // }
    if(this.data.signImg == ''){
      Toast("请签名并确认签名");
      return;
    }

    this.onHttpSubmit(check_state);
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpSubmit: function (check_state) {
    var that = this;
    fetchApi.httpPost('/fire/work/lastCheck', {
        work_id:that.data.fire_work_id,
        check_state: check_state,
        sign_img: that.data.signImg,
        is_submit: that.data.is_submit,
    }, function (res) {
      console.log("发起申请响应数据", res)
      if (res.data.code == 0) {
          Toast.success(res.data.msg);
          // if (that.data.fileList1.length > 0) {
          //   var count = 0;
          //   for (var index in that.data.fileList1) {
          //     wx.uploadFile({
          //       url: fetchApi.getPlatformUrl() + '/fire/work/uploadImg',
          //       filePath: that.data.fileList1[index].url,
          //       name: 'file',
          //       formData: {
          //         fire_work_id: that.data.fire_work_id,
          //         img_type:0,
          //       },
          //       success: function (res) {
          //         console.log('uploadFile success res', res)
          //         var dataJson = JSON.parse(res.data);
          //         if(dataJson.code == 0){
          //             count++;
          //         }
          //         if(count == that.data.fileList1.length){
          //             Toast.success("上传成功");
          //             setTimeout(function(){
          //               wx.navigateBack({
          //                   delta: -1
          //               })
          //             },500)
          //         }
          //       },
          //       fail: function (res) {
          //         console.log('uploadFile fail res', res)
          //       }
          //     })
          //   }
          // }

          setTimeout(function(){
            wx.navigateBack({
                delta: -1
            })
        },500)
      }else{
        Toast.fail(res.data.msg);
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },
  
  preImg: function (t) {
    console.log("preSunImg", t)
    var a = t.currentTarget.dataset.imageindex, e = t.currentTarget.dataset.imgdata || [];
    var c = [];
    for (var index in e) {
      if(e[index].prefix !='mp4'){
        c.push(e[index].imgUrl)
      }
    }
    common_Js.preImg(a, c)    
  },


  /**
  * 以下 - 手写签名 / 上传签名
  */
  startCanvas: function () {//画布初始化执行
    var that = this;
    //获取系统信息
    wx.getSystemInfo({
    success: function (res) {
      canvasw = res.windowWidth;
      canvash = res.windowHeight;
      that.setData({ canvasw: canvasw });
      that.setData({ canvash: canvash });
    }
    }); 
    this.initCanvas();
    this.cleardraw(); 
  },
  //初始化函数
  initCanvas: function () {
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    context.fillStyle = 'rgba(255, 255, 255, 0)';
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
  },
  canvasStart: function (event) {
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
  },
  canvasMove: function (event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    }
    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      }
    }
    context.clearRect(0, 0, canvasw, canvash);
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();
    context.draw(false);
  },
  canvasEnd: function (event) {
    isButtonDown = false;
  },
  //清除画布
  cleardraw: function () {
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
  },
  uploadSignImg(mer_id){
      var that = this
      //生成图片
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        //设置输出图片的宽高
        // destWidth:150, 
        // destHeight:150,
        // fileType:'jpg',
        quality:1.0,
        success: function (res) {
          console.log(res)
          // canvas图片地址 res.tempFilePath
          that.data.signImg = res.tempFilePath;
          wx.uploadFile({
            url: fetchApi.getPlatformUrl() + '/fire/work/uploadSign',
            filePath: res.tempFilePath,
            name: 'file',
            formData: {
              user_id: that.data.user_id,
            },
            success: function (res) {
              console.log('uploadFile success res', res);
              var dataJson = JSON.parse(res.data);
              if(dataJson.code == 0){
                that.data.signImg = dataJson.data.file_name;
                Toast("已上传成功，请处理下一步");
              }
              console.log('that.data.signImg',that.data.signImg)
            },
            fail: function (res) {
              console.log('uploadFile fail res', res)
            }
          })

        },
        fail: function () {
          wx.showModal({
            title: '提示',
            content: 'canvas生成图片失败。微信当前版本不支持，请更新到最新版本！',
            showCancel: false
          });
        },
        complete: function () {}
      })
  }
})